/*global pi */
// 字符串函数模块

pi.mod.define('pi.str', function(pi) {
	"use strict";
	// 定义模块对象
	var module = {};

	// 计算子串在字符串中出现的次数
	module.count = function(str, sub) {
		var len = sub.length,
		i = 0,
		n = 0;
		while ((i = str.indexOf(sub, i)) >= 0) {
			n++;
			i += len;
		}
		return n;
	};
	// 去掉字符串前后的空白字符
	module.strip = function(str) {
		var i, j, n, c;
		for (i = 0, n = str.length; i < n; i++) {
			c = str.charAt(str, i);
			if (c !== " " || c !== "\n" || c !== "\r") {
				break;
			}
		}
		for (j = n - 1; j >= i; j--) {
			c = str.charAt(str, j);
			if (c !== " " || c !== "\n" || c !== "\r") {
				break;
			}
		}
		if (i === 0 && j === n) {
			return str;
		}
		return j > i ? str.slice(i, j + 1) : "";
	};
	// 比较2个字符串的大小 0 表示等于，-1表示小于，1表示大于
	module.compare = function(str1, str2) {
		var c1, c2, r, i = str1.length, n = str2.length;
		if(i > n){
			r = 1;
		}else if(i < n){
			n = i;
			r = -1;
		}else{
			r = 0;
		}
		for (i = 0; i < n; i++) {
			c1 = str1.charCodeAt(i);
			c2 = str2.charCodeAt(i);
			if(c1 === c2) {
				continue;
			}
			return c1 > c2 ? 1 : -1;
		}
		return r;
	};
	// 匹配字符串中的全部匹配的子串
	module.startWith = function(str, sub, ignoreCase) {
		var i, c1, c2, n = sub.length;
		if (str.length < n) {
			return false;
		}
		if (ignoreCase) {
			for (i = 0; i < n; i++) {
				c1 = str.charCodeAt(i);
				c2 = sub.charCodeAt(i);
				if (c1 !== c2) {
					if (c1 >= 65 && c1 <= 90 && (c1 + 32) === c2) {
						continue;
					}
					return false;
				}
			}
		} else {
			for (i = 0; i < n; i++) {
				if (str.charCodeAt(i) !== sub.charCodeAt(i)) {
					return false;
				}
			}
		}
		return true;
	};

	// 匹配字符串中的全部匹配的子串
	module.match = function(str, regExp, recordIndex) {
		var arr = [],
		temp = regExp.exec(str);
		if (recordIndex) {
			while (temp) {
				arr.push(temp[1], regExp.lastIndex);
				temp = regExp.exec(str);
			}
		} else {
			while (temp) {
				arr.push(temp[1]);
				temp = regExp.exec(str);
			}
		}
		return arr;
	};
	// 替换匹配的字符串
	module.replaceMatch = function(str, match, func) {
		var i, j, n, s, arr = pi.str.match(str, match, true);
		for (i = 0, j = 0, n = arr.length; i < n; i += 2) {
			s = arr[i];
			// 将前面的字符串放入数组中
			arr[i] = str.slice(j, arr[i + 1] - s.length - 1);
			j = arr[i + 1] - 1;
			// 调用替换函数
			arr[i + 1] = func(s);
		}
		return (j > 0) ? arr.join("") + str.slice(j) : str;
	};

	return module;
});